﻿using Dysoft.RabbitMQ.Helper;
using RabbitMQ.Client;
using System;
using System.Configuration;
using System.Threading.Tasks;

namespace Dysoft.RabbitMQ
{
    /// <summary>
    /// 生产者模块
    /// </summary>
    public partial class MessageQueue
    {
        /// <summary>
        /// 发布广播消息
        /// </summary>
        /// <typeparam name="T">消息数据类型</typeparam>
        /// <param name="broadcastName">队列名称</param>
        /// <param name="data">消息主体</param>
        /// <remarks>广播消息会将消息发给所有绑定广播的队列</remarks>
        public void Publish<T>(string broadcastName, T data)
        {
            Channel.BasicPublish(
                exchange: ExchangeName,
                routingKey: broadcastName,
                basicProperties: null,
                body: data.ToSerialization());

            ////记录消息发送日志
            //LogMQContent(data);
        }

        /// <summary>
        /// 发布队列消息
        /// </summary>
        /// <typeparam name="T">消息数据类型</typeparam>
        /// <param name="queueName">队列名称</param>
        /// <param name="data">消息主体</param>
        /// <remarks>队列消息会将消息发给指定队列, 注意消息只能被接收一次</remarks>
        public void PublishQueue<T>(string queueName, T data)
        {
            Channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false);
            Channel.BasicPublish(
                exchange: "",
                routingKey: queueName,
                basicProperties: null,
                body: data.ToSerialization());

            ////记录消息发送日志
            //LogMQContent(data);
        }

        /// <summary>
        /// 记录消息发送日志
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        private async Task LogMQContent<T>(T data)
        {
            var flg = Convert.ToBoolean(ConfigurationManager.AppSettings["Rabbitmq.LogToDB"]);
            if (flg)
            {
                //var msg = data.MapTo<MQMsgModel>();
                //var log = new StorageProviders()
                //{
                //    ID = msg.MessageID,
                //    name = msg.MessageTitle,
                //    MessageRouter = msg.MessageRouter,
                //    projectname = msg.MessageSource,
                //    content = msg.MessageContent.ToJsonString(),
                //    Insertdate = msg.SendingTime
                //};

                //if (string.IsNullOrWhiteSpace(log.ID))
                //{
                //    return;
                //}

                ////TODO:记录数据库日志表（通过单例模式）
                //RabbitMQLogServiceSingleton logSingleton = RabbitMQLogServiceSingleton.GetInstance();
                //await logSingleton.WriteMessageLog(msg);
            }

        }

    }
}
